package me.shurufa.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.shurufa.R;
import me.shurufa.bean.Catalog;

/**
 * 目录适配器
 */
public class NewCatalogAdapter extends RecyclerView.Adapter<NewCatalogAdapter.ViewHolder> {

    List<Catalog> dataList;
    Context mContext;

    public NewCatalogAdapter(Context context, List<Catalog> dataList) {
        this.dataList = dataList;
        this.mContext = context;
    }

    @Override
    public NewCatalogAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_book_catalog, parent, false);
        NewCatalogAdapter.ViewHolder holder = new NewCatalogAdapter.ViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(NewCatalogAdapter.ViewHolder holder, int position) {
        Catalog catalog = dataList.get(position);
        holder.bind(catalog);
    }

    public void append(Catalog[] items) {
        int pos = dataList.size();
        for (Catalog item : items) {
            if (!dataList.contains(item))
                dataList.add(item);
        }
        notifyItemRangeInserted(pos, items.length);
    }

    public void append(List<Catalog> items) {
        int pos = dataList.size();
        dataList.addAll(items);
        notifyItemRangeInserted(pos, items.size());
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public void remove(int position) {
        if (dataList.size() > 0) {
            dataList.remove(position);
            this.notifyItemRemoved(position);
        }
    }

    public void clear() {
        int size = dataList.size();
        dataList.clear();
        this.notifyItemRangeRemoved(0, size);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.catalog_title)
        TextView catalogTitle;

        public ViewHolder(View itemView) {
            super(itemView);
            mContext = itemView.getContext();
            ButterKnife.bind(this,itemView);
        }

        /**
         * 绑定数据
         * @param catalog
         */
        public void bind(Catalog catalog){
            if (catalog == null)
                return;
            catalogTitle.setText(catalog.title);
        }
    }
}
